<?php

namespace App\Admin\Controllers\kly;

use App\Models\kly\Kly_camp;
use App\Models\kly\Kly_notice;

use App\Models\kly\Kly_student;
use App\Models\kly\Kly_record;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use App\Admin\Extensions\ExcelExpoter;
use Maatwebsite\Excel\Facades\Excel;
use Encore\Admin\Controllers\HasResourceActions;
use DB;
use App\Models\Student;

class Kly_noticeController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Content $content)
    {
        return $content->header(trans('admin.my_todo_notices'))
            ->description(trans('admin.list'))
            ->body($this->grid());
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id,Content $content)
    {
        return $content
            ->header(trans('admin.attendance_record'))
            ->description(trans('admin.edit'))
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {

    }

    public function show($id, Content $content)
    {
        $notice = Kly_notice::where('id',$id)->get()->toArray();
        //dd($notice_type);
        $num = Kly_record::where('notice_id',$id)->count();
        if ($num == 0) {
            //$crousesheet_id = Notice::where('id',$id)->value('crousesheet_id');
            $student_ids = Kly_student::where('small_camp_id',$notice[0]['camp_id'])->pluck('student_id')->toArray();
            //dd(count($student_ids));
            $data = [];
            for ($i=0; $i <count($student_ids) ; $i++) {
                $data[] = [
                    'notice_id' =>$id,
                    'student_id' =>$student_ids[$i],
                    'status' =>'1',
                    'created_at' => date('Y-m-d H:i:s'),
                    'type' => $notice[0]['type'],
                    'total_score' =>  $notice[0]['total_score']
                ];
            }
            $res = Kly_record::insert($data);
            //自动生成记录后，改变对应的Notice的操作时间，并根据操作时间与截止日期比较更新状态。
            if ($res) {
                $notice = Kly_notice::find($id);
                //dd($notice);
                $notice->operatetime = date('Y-m-d H:i:s');
                if ($notice->operatetime<$notice->endtime&&$notice->status == '1') {
                    $notice->status = '2';
                }

                elseif($notice->operatetime>$notice->endtime&&$notice->status == '1') {
                    $notice->status = '4';
                }
                $notice->save();
            }
        }

        $html = $content
            ->header('事项')
            ->description(trans('admin.detail'))
            ->body(Admin::show(Kly_notice::findOrFail($id), function (Show $show) {
                $show->panel()->tools(function ($tools){
                    $tools->disableDelete();
                    $tools->disableEdit();
                    $tools->disableList();
                });
                $show->id('ID');
                $show->event('事项内容');
                $show->starttime(trans('admin.notice_starttime'));
                $show->endtime(trans('admin.notice_endtime'));

                //不同类型的事项，显示不同的处理
                $notice_id = $show->getModel()->id;
                $notice_type2 = Kly_notice::where('id',$notice_id)->get()->toArray();
                switch ($notice_type2[0]['tag']) {
                    case 'kaoqin':
                        $show->Kly_record('考勤记录', function ($line) {
                            $line->setResource('/admin/Kly_record');
                            //$line->model()->orderBy('id', 'desc');
                            $line->id('序号')->sortable();
                            $line->student_id(trans('admin.en_name'))->display(function($student_id){
                                return Student::find($this->student_id)->en_name;
                            });
                            $line->column(trans('admin.ch_name'))->display(function($student_id){
                                return Student::find($this->student_id)->ch_name;
                            });
                            $line->status(trans('admin.attendance_status'))->radio([
                                1 => '正常',
                                2 => '请假',
                                3 => '迟到',
                                4 => '缺勤',
                                5 => '家长代课',
                            ]);
                            $line->desc('备注')->display(function($desc) {
                                return str_limit($desc, 30, '...');
                            })->editable('textarea');
                            $line->paginate(50);
                            $line->disableActions();
                            $line->disableCreateButton();
                            $line->disableFilter();
                            $line->tools(function ($tools) {
                                $tools->batch(function ($batch) {
                                    $batch->disableDelete();
                                });
                            });
                        });
                        break;
                    case 'test':
                        $show->Kly_record('测试记录', function ($line) {
                            $line->setResource('/admin/Kly_record');
                            //$line->model()->orderBy('id', 'desc');
                            $line->id('序号')->sortable();
                            $line->student_id(trans('admin.en_name'))->display(function($student_id){
                                return Student::find($this->student_id)->en_name;
                            });
                            $line->column(trans('admin.ch_name'))->display(function($student_id){
                                return Student::find($this->student_id)->ch_name;
                            });
                            $line->status('状态')->radio([
                                1 => '正常',
                                2 => '未参加',
                            ]);
                            $line->score('分数')->editable();
                            $line->desc('备注')->display(function($desc) {
                                return str_limit($desc, 30, '...');
                            })->editable('textarea');
                            $line->paginate(50);
                            $line->disableActions();
                            $line->disableCreateButton();
                            $line->disableFilter();
                            $line->tools(function ($tools) {
                                $tools->batch(function ($batch) {
                                    $batch->disableDelete();
                                });
                            });
                        });
                        break;
                    case 'jiaxiao':
                        $show->Kly_record('家校记录', function ($line) {
                            $line->setResource('/admin/Kly_record');
                            //$line->model()->orderBy('id', 'desc');
                            $line->id('序号')->sortable();
                            $line->student_id(trans('admin.en_name'))->display(function($student_id){
                                return Student::find($this->student_id)->en_name;
                            });
                            $line->column(trans('admin.ch_name'))->display(function($student_id){
                                return Student::find($this->student_id)->ch_name;
                            });
                            $line->status(trans('admin.attendance_status'))->radio([
                                1 => '准交',
                                2 => '未交',
                                3 => '补交'
                            ]);
                            $line->score('分数')->editable();
                            $line->desc('备注')->display(function($desc) {
                                return str_limit($desc, 30, '...');
                            })->editable('textarea');
                            $line->paginate(50);
                            $line->disableActions();
                            $line->disableCreateButton();
                            $line->disableFilter();
                            $line->tools(function ($tools) {
                                $tools->batch(function ($batch) {
                                    $batch->disableDelete();
                                });
                            });
                        });
                        break;
                    case 'zuoye':
                        $show->Kly_record('作业记录', function ($line) {
                            $line->setResource('/admin/Kly_record');
                            //$line->model()->orderBy('id', 'desc');
                            $line->id('序号')->sortable();
                            $line->student_id(trans('admin.en_name'))->display(function($student_id){
                                return Student::find($this->student_id)->en_name;
                            });
                            $line->column(trans('admin.ch_name'))->display(function($student_id){
                                return Student::find($this->student_id)->ch_name;
                            });
                            $line->status(trans('admin.attendance_status'))->radio([
                                1 => '准交',
                                2 => '未交',
                                3 => '补交'
                            ]);
                            $line->score('分数')->editable();
                            $line->desc('备注')->display(function($desc) {
                                return str_limit($desc, 30, '...');
                            })->editable('textarea');
                            $line->paginate(50);
                            $line->disableActions();
                            $line->disableCreateButton();
                            $line->disableFilter();
                            $line->tools(function ($tools) {
                                $tools->batch(function ($batch) {
                                    $batch->disableDelete();
                                });
                            });
                        });
                        break;
                    case 'dictation':
                        $show->Kly_record('听写记录', function ($line) {
                            $line->setResource('/admin/Kly_record');
                            //$line->model()->orderBy('id', 'desc');
                            $line->id('序号')->sortable();
                            $line->student_id(trans('admin.en_name'))->display(function($student_id){
                                return Student::find($this->student_id)->en_name;
                            });
                            $line->column(trans('admin.ch_name'))->display(function($student_id){
                                return Student::find($this->student_id)->ch_name;
                            });
                            $line->status(trans('admin.attendance_status'))->radio([
                                1 => '正常',
                                2 => '未参加',
                            ]);
                            $line->score('分数')->editable();
                            $line->desc('备注')->display(function($desc) {
                                return str_limit($desc, 30, '...');
                            })->editable('textarea');
                            $line->paginate(50);
                            $line->disableActions();
                            $line->disableCreateButton();
                            $line->disableFilter();
                            $line->tools(function ($tools) {
                                $tools->batch(function ($batch) {
                                    $batch->disableDelete();
                                });
                            });
                        });
                        break;
                    default:
                        $setting = DB::table('kly_setting')->where('id',$notice_type2[0]['setting_id'])->get();
                        $setting = json_decode(json_encode($setting),true);
                        if($notice_type2[0]['type'] == '1'){
                            $show->Kly_record('记录', function ($line) use ($setting) {
                                $line->setResource('/admin/Kly_record');
                                //$line->model()->orderBy('id', 'desc');
                                $line->id('序号')->sortable();
                                $line->student_id(trans('admin.en_name'))->display(function($student_id){
                                    return Student::find($this->student_id)->en_name;
                                });
                                $line->column(trans('admin.ch_name'))->display(function($student_id){
                                    return Student::find($this->student_id)->ch_name;
                                });
                                $arr = json_decode($setting[0]['status_item'],true);
                                $radio = array();
                                for($i=0;$i<count($arr);$i++){
                                    $radio[$i+1] = $arr[$i];
                                }
                                $line->status('状态')->radio($radio);
                                $line->desc('备注')->display(function($desc) {
                                    return str_limit($desc, 30, '...');
                                })->editable('textarea');
                                $line->paginate(50);
                                $line->disableActions();
                                $line->disableCreateButton();
                                $line->disableFilter();
                                $line->tools(function ($tools) {
                                    $tools->batch(function ($batch) {
                                        $batch->disableDelete();
                                    });
                                });
                            });
                        }elseif($notice_type2[0]['type'] == '2'){
                            $show->Kly_record('记录', function ($line) use ($setting) {
                                $line->setResource('/admin/Kly_record');
                                //$line->model()->orderBy('id', 'desc');
                                $line->id('序号')->sortable();
                                $line->student_id(trans('admin.en_name'))->display(function($student_id){
                                    return Student::find($this->student_id)->en_name;
                                });
                                $line->column(trans('admin.ch_name'))->display(function($student_id){
                                    return Student::find($this->student_id)->ch_name;
                                });
                                $line->score('分数')->editable();
                                $line->desc('备注')->display(function($desc) {
                                    return str_limit($desc, 30, '...');
                                })->editable('textarea');
                                $line->paginate(50);
                                $line->disableActions();
                                $line->disableCreateButton();
                                $line->disableFilter();
                                $line->tools(function ($tools) {
                                    $tools->batch(function ($batch) {
                                        $batch->disableDelete();
                                    });
                                });
                            });
                        }elseif($notice_type2[0]['type'] == '3'){
                            $show->Kly_record('记录', function ($line) use ($setting) {
                                $line->setResource('/admin/Kly_record');
                                //$line->model()->orderBy('id', 'desc');
                                $line->id('序号')->sortable();
                                $line->student_id(trans('admin.en_name'))->display(function($student_id){
                                    return Student::find($this->student_id)->en_name;
                                });
                                $line->column(trans('admin.ch_name'))->display(function($student_id){
                                    return Student::find($this->student_id)->ch_name;
                                });
                                $arr = json_decode($setting[0]['status_item'],true);
                                $radio = array();
                                for($i=0;$i<count($arr);$i++){
                                    $radio[$i+1] = $arr[$i];
                                }
                                $line->status('状态')->radio($radio);
                                $line->score('分数')->editable();
                                $line->desc('备注')->display(function($desc) {
                                    return str_limit($desc, 30, '...');
                                })->editable('textarea');
                                $line->paginate(50);
                                $line->disableActions();
                                $line->disableCreateButton();
                                $line->disableFilter();
                                $line->tools(function ($tools) {
                                    $tools->batch(function ($batch) {
                                        $batch->disableDelete();
                                    });
                                });
                            });
                        }
                        break;
                }
            }));
        Admin::script($this->script());
        return $html;
    }

    public function ignore_notice($id,Request $request)
    {
        $notice = Kly_notice::find($id);
        $notice->status = '5';
        $notice->operatetime = date('Y-m-d H:i:s',time());
        $notice->save();
        return redirect('/admin/Kly_notice/');
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Kly_notice::class, function (Grid $grid) {
            $grid->model()->where(function($query){
                $query->where('tutor_id',Admin::user()->id);
                $query->orWhereRaw('find_in_set('.Admin::user()->id.',`aids`)');
            })->where('status','!=','5');
            $grid->model()->orderBy('starttime', 'ASC');

            $grid->id(trans('admin.ID'))->sortable();
            $grid->column('操作')->display(function(){
                if ($this->starttime<date('Y-m-d H:i:s',time()) && in_array($this->status,['1','3'])) {
                    if(Admin::user()->isAdministrator()){
                        return '<a class="btn btn-primary" href="/admin/Kly_notice/'.$this->id.'">操作</a><a class="btn btn-danger" href="/admin/Kly_notice/ignore/'.$this->id.'">忽略</a>';
                    }else{
                        return '<a class="btn btn-primary" href="/admin/Kly_notice/'.$this->id.'">操作</a>';
                    }
                }elseif($this->starttime<date('Y-m-d H:i:s',time()) && in_array($this->status,['2','4'])){
                    return '<a class="btn btn-success" href="/admin/Kly_notice/'.$this->id.'">查看</a>';
                }else{
                    return '';
                }

            });
            $grid->notice_type(trans('admin.notice_type'))->using(['1' => '考勤', '2' => '测试', '3' => '家校', '4' => '听写','5' => '作业','6'=>'自定义'])->sortable();
            $grid->event(trans('admin.notice_event'))->style('max-width:600px;word-break:break-all;');
            $grid->starttime(trans('admin.notice_starttime'))->sortable();
            $grid->endtime(trans('admin.notice_endtime'))->sortable();
            $grid->status(trans('admin.status'))->display(function($status){
                if ($this->status == '1') {
                    return "<span class='label bg-orange'>待完成</span>";
                }elseif ($this->status == '2') {
                    return "<span class='label bg-green'>已完成</span>";
                }
                elseif ($this->status == '3') {
                    return "<span class='label bg-red'>逾期</span>";
                }
                elseif ($this->status == '4') {
                    return "<span class='label bg-yellow'>补录完成</span>";
                }elseif ($this->status == '5') {
                    return "<span class='label bg-navy'>忽略</span>";
                }
            })->sortable();
            //$grid->operatetime(trans('admin.notice_operatetime'))->sortable();

            $grid->disableCreateButton();
            //$grid->disableFilter();
            $grid->disableExport();
            //$grid->disableRowSelector();
            $grid->disableActions();
/*            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
            });*/
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    //$batch->add('忽略', new IgnoreNotice(5));
                    $batch->disableDelete();
                });
            });

            //筛选弹出框字段
            $grid->filter(function ($filter) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->expand();

                $filter->in('status','状态')->multipleSelect(['1'=>'待完成','2'=>'已完成','3'=>'逾期','4'=>'补录完成','5'=>'忽略']);
                $filter->in('notice_type','类型')->multipleSelect(['1'=>'考勤记录','2'=>'测试记录','3'=>'家校记录','4'=>'听写记录','5'=>'作业记录','6'=>'自定义']);
                $squad_ids = Kly_camp::where(function($query){
                    $query->where('tutors',Admin::user()->id);
                    $query->orWhereRaw('find_in_set('.Admin::user()->id.',`aids`)');
                })->pluck('name','id')->toArray();
                // dd($squad_ids);
                $filter->in('camp_id','小营')->multipleSelect($squad_ids);
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {

    }

    public function script()
    {
        return <<<SCRIPT

        save=function(id,type,max){
            var score = $('#'+id+'-score').val();
            if(score > max){
                toastr.error('分数已超过总分，请修改！');
                return;
            }
            $.ajax({
                method: 'PUT',
                url: '/admin/test_score_record/'+id,
                data: {
                    _token:LA.token,
                    value:score,
                    pk:id,
                    name:'test_score',
                    _editable:1
                },
                success: function () {
                    toastr.success('修改成功');
                },
                error: function () {
                    toastr.error('修改失败');
                }
            });
        }

        $(".score").on('keydown',function (e) {
                if (e.which == 13) {
                    $(this).next().click();
                }
        });

SCRIPT;
    }
}
